package com.haidechizi.fastadmin.modules.gen.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.haidechizi.fastadmin.common.enums.DelFlagEnum;
import com.haidechizi.fastadmin.common.page.PageDto;
import com.haidechizi.fastadmin.common.utils.PageInfo;
import com.haidechizi.fastadmin.common.utils.StringUtils;
import com.haidechizi.fastadmin.modules.gen.dao.GenDataBaseDictDao;
import com.haidechizi.fastadmin.modules.gen.dao.GenTableColumnDao;
import com.haidechizi.fastadmin.modules.gen.dao.GenTableDao;
import com.haidechizi.fastadmin.modules.gen.entity.GenTable;
import com.haidechizi.fastadmin.modules.gen.entity.GenTableColumn;
import com.haidechizi.fastadmin.modules.gen.service.GenTableService;
import com.haidechizi.fastadmin.modules.gen.util.GenUtils;
import com.haidechizi.fastadmin.modules.sys.entity.SysOffice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;

/**
 * 业务表service
 */
@Service
@Transactional
public class GenTableServiceImpl extends ServiceImpl<GenTableDao, GenTable> implements GenTableService {

    @Autowired
    private GenTableDao genTableDao;

    @Autowired
    private GenTableColumnDao genTableColumnDao;

    @Autowired
    private GenDataBaseDictDao genDataBaseDictDao;

    @Value("${jdbc.type:mysql}")
    private String jdbcType;

    @Override
    public GenTable get(Long id) {
        GenTable genTable = genTableDao.selectById(id);
        List<GenTableColumn> columnList = genTableColumnDao.selectList(
                new EntityWrapper<GenTableColumn>().eq("gen_table_id", genTable.getId()));
        genTable.setColumnList(columnList);
        return genTable;
    }

    @Override
    public PageInfo findPage(PageDto pageDto, GenTable genTable) {
        Wrapper<GenTable> wrapper;
        Page<GenTable> page = this.selectPage(
                pageDto.cover2Page(),
                wrapper = new EntityWrapper<GenTable>()
                        .eq(StringUtils.isNotBlank(genTable.getName()), "name", genTable.getName())
        );
        int count = super.selectCount(wrapper);
        page.setTotal(count);
        return new PageInfo(page);
    }


    /**
     * 获取物理数据表列表
     *
     * @param genTable
     * @return
     */
    @Override
    public List<GenTable> findTableListFormDb(GenTable genTable) {
        genTable.setDbName(jdbcType);
        return genDataBaseDictDao.findTableList(genTable);
    }

    /**
     * 验证表名是否可用，如果已存在，则返回false
     *
     * @param tableName
     * @return
     */
    @Override
    public boolean checkTableName(String tableName) {
        if (StringUtils.isBlank(tableName)) {
            return true;
        }
        List<GenTable> list = genTableDao.selectList(new EntityWrapper<GenTable>().eq("name", tableName));
        return list.size() == 0;
    }

    /**
     * 获取物理数据表列表
     *
     * @param genTable
     * @return
     */
    @Override
    public GenTable getTableFormDb(GenTable genTable) {
        // 如果有表名，则获取物理表
        if (StringUtils.isNotBlank(genTable.getName())) {
            genTable.setDbName(jdbcType);
            List<GenTable> list = genDataBaseDictDao.findTableList(genTable);
            if (list.size() > 0) {

                // 如果是新增，初始化表属性
                if (genTable.getId() == null || genTable.getId() < 0) {
                    genTable = list.get(0);
                    // 设置字段说明
                    if (StringUtils.isBlank(genTable.getComments())) {
                        genTable.setComments(genTable.getName());
                    }
                    genTable.setClassName(StringUtils.toCapitalizeCamelCase(genTable.getName()));
                }

                // 添加新列
                genTable.setDbName(jdbcType);
                List<GenTableColumn> columnList = genDataBaseDictDao.findTableColumnList(genTable);
                for (GenTableColumn column : columnList) {
                    boolean b = false;
                    for (GenTableColumn e : genTable.getColumnList()) {
                        if (e.getName().equals(column.getName())) {
                            b = true;
                        }
                    }
                    if (!b) {
                        genTable.getColumnList().add(column);
                    }
                }

                // 删除已删除的列
                for (GenTableColumn e : genTable.getColumnList()) {
                    boolean b = false;
                    for (GenTableColumn column : columnList) {
                        if (column.getName().equals(e.getName())) {
                            b = true;
                        }
                    }
                    if (!b) {
                        e.setDelFlag(DelFlagEnum.DEL.getValue());
                    }
                }

                // 获取主键
                genTable.setPkList(genDataBaseDictDao.findTablePK(genTable));

                // 初始化列属性字段
                GenUtils.initColumnField(genTable);

            }
        }
        return genTable;
    }


    @Transactional(readOnly = false)
    public void save(GenTable genTable) {
        genTableDao.insert(genTable);
        // 保存列
        for (GenTableColumn column : genTable.getColumnList()) {
            column.setGenTableId(genTable.getId());
            if(SysOffice.class.getName().equals(column.getJavaType())) {
                column.setShowType("officeSelect");
            }
            genTableColumnDao.insert(column);
        }
    }

    /**
     * 更新
     *
     * @param genTable
     */
    @Override
    public void update(GenTable genTable) {
        genTableDao.updateById(genTable);
        // 保存列
        for (GenTableColumn column : genTable.getColumnList()) {
            column.setGenTableId(genTable.getId());
            if(SysOffice.class.getName().equals(column.getJavaType())) {
                column.setShowType("officeSelect");
            }
            genTableColumnDao.updateById(column);
        }
    }

    /**
     * 删除
     *
     * @param ids
     */
    @Override
    public void delete(Long[] ids) {
        super.deleteBatchIds(Arrays.asList(ids));
        for (Long id : ids) {
            genTableColumnDao.deleteByGenTableId(id);
        }
    }

    /**
     * 获取表的列
     *
     * @param genTable
     * @return
     */
    @Override
    public List<GenTableColumn> findTableColumnList(GenTable genTable) {
        genTable.setDbName(jdbcType);
        return genDataBaseDictDao.findTableColumnList(genTable);
    }
}
